package com.kh.rationaldrugreview.service;

import com.kh.rationaldrugreview.dto.PrescriptionRiskAssessmentRequest;
import com.kh.rationaldrugreview.dto.PrescriptionRiskAssessmentResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 知识图谱风险评估服务
 * Knowledge Graph Risk Assessment Service
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class KnowledgeGraphRiskAssessmentService {
    
    private final RiskAssessmentEngine riskAssessmentEngine;
    
    /**
     * 执行基于知识图谱的风险评估
     */
    public PrescriptionRiskAssessmentResponse assessPrescriptionRisk(PrescriptionRiskAssessmentRequest request) {
        log.info("Starting knowledge graph-based risk assessment for {} drugs", 
            request.getDrugs() != null ? request.getDrugs().size() : 0);
        
        try {
            // 验证请求参数
            validateRequest(request);
            
            // 调用风险评估引擎
            PrescriptionRiskAssessmentResponse response = riskAssessmentEngine.assess(request);
            
            log.info("Risk assessment completed successfully. Assessment ID: {}, Overall Risk: {}", 
                response.getAssessmentId(), response.getOverallRiskLevel());
            
            return response;
            
        } catch (IllegalArgumentException e) {
            log.warn("Invalid request parameters: {}", e.getMessage());
            return createErrorResponse("INVALID_REQUEST", e.getMessage());
        } catch (Exception e) {
            log.error("Risk assessment failed", e);
            return createErrorResponse("ASSESSMENT_ERROR", "风险评估过程中发生错误：" + e.getMessage());
        }
    }
    
    /**
     * 批量风险评估
     */
    public PrescriptionRiskAssessmentResponse batchAssess(PrescriptionRiskAssessmentRequest... requests) {
        log.info("Starting batch risk assessment for {} requests", requests.length);
        
        // 简化实现：依次评估并合并结果
        // 实际应用中可以考虑更复杂的批量处理逻辑
        
        PrescriptionRiskAssessmentResponse firstResponse = null;
        int totalRisks = 0;
        
        for (PrescriptionRiskAssessmentRequest request : requests) {
            PrescriptionRiskAssessmentResponse response = assessPrescriptionRisk(request);
            
            if (firstResponse == null) {
                firstResponse = response;
            }
            
            if (response.getRiskItems() != null) {
                totalRisks += response.getRiskItems().size();
            }
        }
        
        if (firstResponse != null) {
            firstResponse.setSummary(String.format("批量评估完成，共发现 %d 项风险", totalRisks));
        }
        
        return firstResponse != null ? firstResponse : 
            createErrorResponse("BATCH_ERROR", "批量评估失败");
    }
    
    /**
     * 快速风险筛查（只检查高风险项）
     */
    public PrescriptionRiskAssessmentResponse quickScreening(PrescriptionRiskAssessmentRequest request) {
        log.info("Starting quick risk screening");
        
        // 修改评估选项，只包含高风险检查
        PrescriptionRiskAssessmentRequest.AssessmentOptions quickOptions = 
            PrescriptionRiskAssessmentRequest.AssessmentOptions.builder()
                .checkInteractions(true)
                .checkContraindications(true)
                .checkPregnancy(true)
                .checkAllergies(true)
                .checkAge(false)          // 跳过年龄检查
                .checkOrganFunction(true)
                .checkDuplication(false)  // 跳过重复用药检查
                .generateRecommendations(true)
                .assessmentLevel("快速")
                .includeMinorRisks(false) // 只包含高风险项
                .prioritizeByRisk(true)
                .build();
        
        request.setOptions(quickOptions);
        
        return assessPrescriptionRisk(request);
    }
    
    /**
     * 验证请求参数
     */
    private void validateRequest(PrescriptionRiskAssessmentRequest request) {
        if (request == null) {
            throw new IllegalArgumentException("请求参数不能为空");
        }
        
        if (request.getPatient() == null) {
            throw new IllegalArgumentException("患者信息不能为空");
        }
        
        if (request.getDrugs() == null || request.getDrugs().isEmpty()) {
            throw new IllegalArgumentException("处方药品列表不能为空");
        }
        
        // 验证药品信息
        for (PrescriptionRiskAssessmentRequest.PrescriptionDrug drug : request.getDrugs()) {
            if (drug.getDrugName() == null || drug.getDrugName().trim().isEmpty()) {
                throw new IllegalArgumentException("药品名称不能为空");
            }
        }
        
        // 验证患者基本信息
        if (request.getPatient().getAge() != null && 
            (request.getPatient().getAge() < 0 || request.getPatient().getAge() > 150)) {
            throw new IllegalArgumentException("患者年龄不合理");
        }
        
        if (request.getPatient().getWeight() != null && 
            (request.getPatient().getWeight() <= 0 || request.getPatient().getWeight() > 1000)) {
            throw new IllegalArgumentException("患者体重不合理");
        }
    }
    
    /**
     * 创建错误响应
     */
    private PrescriptionRiskAssessmentResponse createErrorResponse(String errorCode, String errorMessage) {
        return PrescriptionRiskAssessmentResponse.builder()
            .assessmentId("ERROR_" + System.currentTimeMillis())
            .status(PrescriptionRiskAssessmentResponse.AssessmentStatus.ERROR)
            .summary("风险评估失败：" + errorMessage)
            .riskItems(java.util.List.of())
            .recommendations(java.util.List.of())
            .details(PrescriptionRiskAssessmentResponse.AssessmentDetails.builder()
                .errors(java.util.List.of(errorCode + ": " + errorMessage))
                .build())
            .assessmentTime(java.time.LocalDateTime.now())
            .build();
    }
}